<template>
  <div>
      <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/admin/banner/list">轮播图管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>轮播图列表</el-breadcrumb-item>
    </el-breadcrumb><br/>


    <!--按钮：添加轮播图-->
    <el-button type="primary" round @click="cardPopup(0)">添加轮播图</el-button>

    <!--按钮：批量删除-->
    <el-button type="danger" round @click="handleDeleteList()">批量删除</el-button><br/><br/>

    <template>
    <!--轮播图列表-->
    <el-table
        :data="tableData"
        ref="multipleTable"
        border
        style="width: 100%"
        @selection-change="handleSelectChange"
        >
      <el-table-column
          type="selection"
          width="50">
      </el-table-column>
      <el-table-column prop="id" label="序号" width="150"></el-table-column>
      <el-table-column prop="url" label="图片地址" width="150">
        <template slot-scope="scope">
          <el-avatar
              :size="80"
              :src="scope.row.url"
          ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="轮播图的状态" width="180">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.status==1?'显示':'不显示'">
            <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inacti
                :active-value="1"
                :inactive-value="0"
                @change="handleEdit(scope.row)">
            </el-switch>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="gmtCreate" label="添加时间" width="180"></el-table-column>
      <el-table-column prop="gmtModified" label="修改时间" width="180"></el-table-column>

      <!--添加或修改分类-->
      <el-table-column label="操作">
        <template slot-scope="scope" style="float: left">
          <el-tooltip class="item" effect="dark" content="修改轮播图" placement="top">
          <el-button type="primary" icon="el-icon-edit" circle  @click="cardPopup(scope.row.id);selectById(scope.row.id)"></el-button>
          </el-tooltip>

          <el-tooltip class="item" effect="dark" content="删除轮播图" placement="top">
            <el-button type="danger" icon="el-icon-delete" circle
                       @click="openDeleteConfirm(scope.row.id)"></el-button>
          </el-tooltip>
        </template>

      </el-table-column>

    </el-table>
</template>

<!--添加或修改弹窗-->
<template>
  <div>
    <el-dialog
        append-to-body
        :title = dialogVisibleTitle
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="40%"
        @close="closeDialog('ruleForm')">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm">
        <el-form-item label="轮播图" prop="url">
          <el-input v-model="ruleForm.url" maxlength="255" show-word-limit clearable
                    style="width: 300px;"></el-input>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" @click="submitForm()">提交</el-button>
          <el-button @click="closeDialog('ruleForm')">重置</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    </div>
  </template>

    <!--页码-->
    <template>
      <div>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="Page"
            :page-sizes="[5, 7, 10, 20]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="countDate">
        </el-pagination>
      </div>
    </template>

  </div>
</template>

$("input[serch=true]").on("propertychange input change", function() {
seach();
});
<script>
export default {
  data() {
    return {
      input:{
        id:'',
        status:'',
        offset: '',
        count: '',
      },
      ruleForm:{
        id:'',
        url:''
      }, // 添加 / 修改数据集
      tableData: [], // 条件查询结果集
      multipleSelection: [], // 批量删除复选框
      optionsSelectEcho:[],       // 分类数据回显
      rules:
          {
            'name': [{required: true,message: '必填字段',trigger: 'blur'}],
          },

      dialogVisible:false, // 弹出框状态【添加 or 修改功能】，默认隐藏
      dialogVisibleTitle:'添加分类',

      Page: 1,   // 当前页码
      pageSize: 5,   // 每页展示信息数量
      countDate: 0,     // 条件查询结果集数量

      AddOrSetByBannerId:0,              // 区别方法【添加 ro 修改】
    }
  },
  methods:{

    /**
     * 弹窗：添加业务 OR 修改业务
     */
    cardPopup(bannerId) {
      if (bannerId === 0) {
        this.AddOrSetByBannerId = 0;          // 调用添加方法
        this.dialogVisibleTitle = "添加轮播图"; // 设置弹窗标题
      } else {
        this.dialogVisibleTitle = "修改轮播图"; // 设置弹窗标题
        this.AddOrSetByBannerId = bannerId;     // 调用修改方法
      }
      this.dialogVisible = true;   // 打开弹窗
    },
    /**
     * 业务：添加 OR 修改
     */
    submitForm() {
      let addOrSetData = this.ruleForm;

      if (this.AddOrSetByBannerId === 0) {
        console.log("即将向服务器发送【添加轮播图】请求，参数：{"+
            "url="+addOrSetData.url+
            "}")

        let url = "http://localhost:9090/banner/insert"
        /**
         * 添加伦播图
         */
        this.axios.post(url, addOrSetData).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: "创建成功"
              });
              this.loadBanner()
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      } else {
        let url ="http://localhost:9090/banner/update"
        console.log("即将向服务器发送【修改轮播图】请求，参数：{"+
            "url="+addOrSetData.url+
            "}")
        /**
         * 修改分类
         */
        this.axios.post(url, addOrSetData).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '修改轮播图成功!'
              });
              this.optionsSelectEcho=[];
              this.loadBanner()
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      }
      this.closeDialog();
      this.dialogVisible = false;   // 关闭弹窗
    },
    /*通过id查询*/
    selectById(id) {
      this.axios.get("http://localhost:9090/banner/"+ id +"/selectById").then((response)=> {
        console.log(response)
        this.ruleForm=response.data.data;
      })
    },
    /**
     * 业务：修改轮播图状态
     * @param id
     */
    handleEdit(row) {
      this.$confirm('此操作将使【'+row.status+'】的状态改变, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let path = "http://localhost:9090/banner/update"
        let data = {
          id: row.id,
          status: row.status
        }
        /**
         * 修改根据用户id修改用户状态
         */
        this.axios.post(path, data).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: "修改成功"
              })
              this.listUsersByCondition();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              if (row.status === 0) {
                row.status = 1;
              } else {
                row.status = 0;
              }
              break;
          }
        })
      }).catch(() => {
        if (row.status === 0) {
          row.status = 1;
        } else {
          row.status = 0;
        }
      })
    },
    /**
     * 删除方法
     */
    handleDelete(id) {
      console.log('将删除id=' + id + '的分类');
      this.axios.post("http://localhost:9090/banner/" + id + "/delete").then((response) => {
        let json = response.data;
        if(json.code == 200){
          this.$message({
            message: '删除轮播图成功!',
            type: 'success'
          });
        }else {
          this.$message.error(response.data.message);
        }
        this.loadBanner();
      })
    },
    /**
     * 删除确认框
     */
    openDeleteConfirm(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(id);
      }).catch(() => {
      });
    },
    /**
     * 分页查询
     */
    listBannerBy(){
        this.input.offset = (this.Page - 1) * this.pageSize;
        this.input.count = this.pageSize;

        /**
         * 查询满足查询条件的信息数量
         */
        this.axios.post("http://localhost:9090/banner/countAll",this.input).then((response) => {
          this.countDate = response.data;
        })
        /**
         * 查询满足查询条件的分类列表
         */
        this.axios.post("http://localhost:9090/banner/listByBanner",this.input).then((response) => {
          this.tableData = response.data;
        })
    },
    /**
     * 复选框
     * @param val
     */
    handleSelectChange(val) {
      this.multipleSelection = val;
    },
    /**
     * 批量删除
     */
    handleDeleteList() {
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: 'info',
          message: '请勾选需要删除的类别'
        });
        return;
      }
      let array = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        array.push(this.multipleSelection[i].id);
      }

      this.$confirm('此操作将永久删除ID为【'+array+'】的用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post("http://localhost:9090/banner/deletes", array).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.loadBanner()
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      }).catch(() => {
        this.$refs.multipleTable.clearSelection();
        this.$message({
          type: 'info',
          message: '已取消批量删除'
        });
      });
    },
    /**
     * 刷新页面,获取数据
     */
    loadBanner(){
      let url = "http://localhost:9090/banner/list?page=1&pageSize=6";
      console.log('url = ' + url);
      this.axios.get(url).then((response) => {
        let json = response.data;
        console.log(json)
        if(json.code == 200){
          // let list = json.data;
          // for (let i = 0; i < list.length; i++) {
          //   console.log(list[i]);
          // }
          this.tableData = json.data.list;
        }else {
          this.$message.error(response.data.message);
        }
      });
    },

    /**
     * 清除弹窗数据及遗留效果
     */
    closeDialog(ruleForm) {
      this.ruleForm = {}
      if (this.$refs[ruleForm] !== undefined) {
        this.$refs[ruleForm].resetFields();
      }
    },

    /**
     * 业务：获取分页，每页条数
     * @param val
     */
    handleSizeChange(val) {
      console.log(`当前每页 ${val} 条`);
      this.pageSize = val;
      this.listBannerBy();
    },

    /**
     * 业务：获取当前页数
     * @param val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.Page = val;
      this.listBannerBy();
    },


    clearSelection() {
      this.store.clearSelection();
    },
  },
  created() {
    //created >>> 已创建,将在mounted, 显示页面之前执行
    this.loadBanner();
  }
}
</script>
